const { WechatUploader } = require('./utils/wechat-uploader');
const agentUpload = require('./utils/agent-upload');
const { obfuscate } = require('./utils/obfuscator');
const { JSDOM } = require('jsdom');
require('dotenv').config();
const pug = require('pug')
const fs = require('fs').promises;
const fsys = require('fs');
const path = require('path');

const attrs = require(path.join(__dirname, '../src/data/attrs.json'))
const audiUrls = require(path.join(__dirname, '../src/data/audi.json'))
const fordUrls = require(path.join(__dirname, '../src/data/ford.json'))
const mockUrls = require(path.join(__dirname, '../src/data/mock.json'))


module.exports = async (projectName, options) => {
  try {

    const projectPath = path.join(__dirname, `../projects/${projectName}`);
    const cssObject = await readCssFile();

    console.log(projectPath, options)

    /*
     * 使用服务器代理上传图片, 完成后更新urls.json
     */
    const urlPath = path.join(__dirname, `../projects/${projectName}`, 'urls.json')
    const urlJson = require(urlPath);
    for (let index = 0; index < urlJson.length; index++) {
      const file = urlJson[index]?.file;
      const imgPath = path.join(__dirname, `../projects/${projectName}/images`, file)

      // if (!fsys.existsSync(imgPath) || !options.includes['UploadImages']) { continue }
      const imgUrl = await localUploader(imgPath)
      urlJson[index].url = imgUrl

      // agentUpload()
    }

    // update urls.json
    fsys.writeFileSync(
      urlPath,
      JSON.stringify(urlJson, null, 2)
    );

    const templateData = {
      images: urlJson,
      ...attrs,
      audiUrls,
      fordUrls,
      mockUrls,
      process: process.env,
    }
    // console.log(templateData)
    // return
    // 生成最终HTML

    const html = pug.renderFile(`${projectPath}/home.pug`, templateData);
    const cleanedHtml = removeHtmlComments(html);
    const dom = new JSDOM(cleanedHtml)
    const rootElement = dom.window.document.getElementById('root');

    if (!rootElement) {
      throw new Error('模板中未找到 #root 元素');
    }

    //写入内联style
    Object.keys(cssObject).forEach(key => {
      if (key.includes('*')) { return }
      const className = `.${key}`
      console.log(className)
      const styleStr = Object.entries(cssObject[key])
        .map(([key, value]) => `${key.replace(/([A-Z])/g, '-$1').toLowerCase()}: ${value};`)
        .join('');
      rootElement.querySelectorAll(className)?.forEach(elem => {
        const orginStyle = elem.getAttribute('style') || ''
        elem.setAttribute('style', styleStr + orginStyle)
      })
    })

    const rootContent = rootElement.innerHTML;

    // 添加混淆, 有问题还不能用
    // const finalCode = obfuscate(code);

    // 确保目录存在
    if (!fsys.existsSync(projectPath)) {
      fsys.mkdirSync(projectPath, { recursive: true });
    }

    // 使用绝对路径写入文件
    const outputPath = path.join(projectPath, 'code.txt');
    fsys.writeFileSync(outputPath, rootContent.trim());
    console.log(`✅ 已生成文件: ${outputPath}`);

    return outputPath; // 返回生成的文件路径
  } catch (error) {
    console.error('编译过程中出现错误:', error);
    throw error; // 重新抛出错误，确保调用者知道发生了错误
  }
};

async function readJsonFile(jsonPath) {
  try {
    const data = await fs.readFile(jsonPath, 'utf8');
    const jsonData = JSON.parse(data);
    // console.log(jsonData);
    return jsonData
  } catch (err) {
    console.error('Error:', err);
  }
}

// 删除 HTML 中的注释
function removeHtmlComments(html) {
  return html.replace(/<!--[\s\S]*?-->/g, '');
}

/* 
 * 使用微信API 在本机直接上传图片
 */
async function localUploader(imgPath) {
  const uploader = new WechatUploader({
    appId: process.env.WECHAT_APP_ID,
    appSecret: process.env.WECHAT_API_SECRET,
  });
  const url = await uploader.uploadMedia(imgPath);
  return url
}


// 读取和解析 CSS 文件
const readCssFile = async () => {
  const cssPath = path.join(__dirname, '../assets/styles', 'pug.css');
  // 检查文件是否存在
  if (!fsys.existsSync(cssPath)) { console.warn('未找到 pug.css 文件'); }
  try {
    const cssContent = fsys.readFileSync(cssPath, 'utf-8');
    console.log('CSS 文件内容读取成功！');
    return parseCss(cssContent); // 返回解析后的 CSS 对象
  } catch (error) {
    console.error('读取 CSS 文件失败:', error.message);
  }
}

// 解析 CSS 内容为对象
const parseCss = (cssContent) => {
  const rules = {};
  // 基本解析 CSS
  cssContent.split('}').forEach(rule => {
    const [selector, styles] = rule.split('{');
    if (!(selector && styles)) { return; }
    const className = selector.trim().replace('.', ''); // 去掉前面的点
    rules[className] = styles.split(';').reduce((acc, style) => {
      const [property, value] = style.split(':').map(s => s.trim());
      if (property && value) { acc[property] = value; }
      return acc;
    }, {});
  });

  return rules;
};
